var express = require('express');
var router = express.Router();
var utils = require('../../functions/utils');

router.get('/' , function(req,res)
{
	var html = "<form name='tmpForm' method='post' action='/push'></form>";
	html +=	"<script language=javascript>tmpForm.submit();</script>";

	res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
	res.end(html);

});

router.post('/' , function(req,res)
{

	var message		= req.body.message;
	var articleUrl  = req.body.articleUrl;

	var sessionKey = req.session.key;

	var canStartPush = false;

	if(utils.isValidString(sessionKey))
	{
		var async = require('async');
		async.waterfall([
			function(cb)
			{
				utils.checkManagerSession(sessionKey , cb);
			}
			,function(result , cb) 
			{
				// 실패 - 로그인 페이지 
				if(result == 0)
				{
					utils.notifyManagerSessionExpired(req , res);
				}
				// 성공 - 실제 작업코드.
				else
				{

					utils.debug(req.originalUrl);

					var fs = require('fs');
					fs.readFile('./template/push' , function(error,data)
					{
						if(error)
						{
							throw error;
						}
						var html = String(data);

						global.replica_db.connection.getConnection(function(err,connection)
						{
							if(err) throw err;

							var sql = "call manage_getTimezonePushWorkingCount()";
							var query = connection.query(sql, null , function (err, rows) 
							{
								connection.release();
								if(err) throw err;

								// 이미 보내고 있다고 보여주기 때문에 기존에 보내고 있는 메시지로 바꾼다.
								canStartPush = rows[0][0].workingCount == 0;
								if(!canStartPush)
								{
									message = rows[0][0].message;
									articleUrl = rows[0][0].articleUrl;
								}

								var status = '';

								if(canStartPush)
								{
									status += '<br> You can push message.';

									html = html.split("%MESSAGE_READONLY%").join('');
									html = html.split("%BUTTON_DISABLED%").join('');
								}
								else
								{
									status += '<br> You can not push message. Previous job is ongoing : ['+rows[0][0].workingCount+'] time zone(s)';

									status += '<br><b>'
									for(var i = 0 ; i < rows[1].length ; i ++)
									{
										if(rows[1][i].isFinished)
											status += '<font color=blue>'+rows[1][i].workHour+'</font>&nbsp;';
										else
											status += '<font color=red>'+rows[1][i].workHour+'</font>&nbsp;';
									}
									status +='</b><br>';

									html = html.split("%MESSAGE_READONLY%").join('READONLY');
									html = html.split("%BUTTON_DISABLED%").join('DISABLED');
								}


								if(utils.isValidString(message))
									html = html.split("%MESSAGE%").join(message);
								else
									html = html.split("%MESSAGE%").join('');


								if(utils.isValidString(articleUrl))
									html = html.split("%ARTICLE_URL%").join(articleUrl);
								else
									html = html.split("%ARTICLE_URL%").join('');


								html = html.split("%TIMEZONE_STATUS%").join(status);

								res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
								res.end(html);

							}); // replica select query

						}); // replica connection	

					}); // read template file
				}
			}
		]); //waterfall
	}
	// 암것도 없으면 loginPage
	else
	{
		utils.gotoManagerLoginPage(req , res);
	}
});

module.exports = router;